Code Snippets

This is bringing together my code notes from various place into one place.

Search files in the directory


In [ ]:
import os, fnmatch
# This is a function to locate xml files under the directory
def locate(pattern, root=os.curdir):
    location = os.walk(os.path.abspath(root))
    for path, dirs, files in location:
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

In [ ]:
# get txt collection from directory and place it in memory
collection = locate("*.txt")

In [ ]:
for index, location in enumerate(collection):
    print index,location

Output is something like 0 /Users/Folder1/Folder1.1/This is ab copy.txt 1 /Users/Folder1/Folder1.1/This is ab copy.txt

It works!